//---------------------------------------------------------------------
// Author: jachymko
//
// Description: PS item name expansion handler
//
// Creation Date: Jan 9, 2007
//---------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Management.Automation;
using System.Text.RegularExpressions;
using BGShell.PowerShell.Commands;

namespace BGShell.PowerShell.TabExpansion.Handlers
{
    internal sealed class ItemPathHandler : TabExpansionHandler
    {
        public ItemPathHandler(GetTabExpansionCommand command)
            : base(command)
        {

        }

        public override bool TryExpand(string line, string word)
        {
            var sessionPath = Command.SessionState.Path;
            var location = sessionPath.CurrentLocation;
            var provider = location.Provider;

            var providerName = provider.PSSnapIn.Name + "\\" + provider.Name;
            var cwd = providerName + "::" + location.ProviderPath;

            ICollection<PSObject> objects;

            try
            {
                objects = Command.InvokeProvider.ChildItem.Get(word + '*', false);
            }
            catch(ProviderInvocationException)
            {
                return true;
            }

            foreach (var obj in objects)
            {
                var prop = obj.Properties["PSPath"];

                if (prop != null)
                {
                    var pspath = prop.Value as string;

                    if (pspath != null)
                    {
                        ProviderInfo childProvider;
                        PSDriveInfo childDrive;

                        var providerPath = sessionPath.GetUnresolvedProviderPathFromPSPath(pspath, out childProvider, out childDrive);
                        var parent = sessionPath.ParseParent(pspath, null);

                        if (cwd.Equals(parent, StringComparison.Ordinal))
                        {
                            pspath = pspath.Substring(parent.Length);

                            if ((pspath[0] == '\\') || (pspath[0] == '/'))
                            {
                                pspath = '.' + pspath;
                            }
                            else
                            {
                                pspath = ".\\" + pspath;
                            }
                        }
                        else
                        {
                            pspath = providerPath;
                        }

                        WriteExpansions(pspath);
                    }
                }
            }

            return true;
        }
    }
}
